package club.jdiy.core.storage;

import club.jdiy.core.ex.JDiyException;
import club.jdiy.core.sql.Args;
import club.jdiy.core.sql.Dao;
import club.jdiy.core.sql.Rs;
import club.jdiy.utils.JsonUtils;
import club.jdiy.utils.StringUtils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * JDiy 附件存储MetaData持久化代理类.
 *
 * @author ziquee(子秋) QQ号:39886616 主页: http://www.jdiy.club
 * @version 20200725
 */
public class StoreHandler implements InvocationHandler {
    private final Store store;
    private final String dataId;
    private final Dao dao;


    public StoreHandler(Dao dao, Store o, String dataId) {
        this.dao = dao;
        this.store = o;
        this.dataId = dataId;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String mn = method.getName();
        if (!mn.startsWith("get") && !mn.startsWith("put") && ("0".equals(((StoreSaver) store).getDataId()) || StringUtils.isEmpty(((StoreSaver) store).getDataId())))
            throw new JDiyException("Store存储失败，主键为空或者值为0．");

        Object ret = method.invoke(store, args);

        if (method.isAnnotationPresent(Store.AutoSave.class)) {
            StoreMetaData storeMetaData = ((StoreSaver) store).getStoreData();
            if (storeMetaData.getItems().size() < 1) {
                dao.del(new Args("jdiy_store", "id='" + dataId + "'"));
            } else {
                Rs rs = dao.rs("jdiy_store", dataId);
                rs.set(rs.getPrimaryKey(), dataId)
                        .set("data", JsonUtils.stringify(storeMetaData));
                dao.save(rs);
            }
        }
        return ret;
    }

}
